<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2012  <>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 * Hint: use extdeveval to insert/update function index above.
 */

require_once(PATH_tslib.'class.tslib_pibase.php');
require_once(t3lib_extMgm::extPath("mtkatalogi_add")."/test.php");

/**
 * Plugin 'Dodawanie wpisu' for the 'mtkatalogi_add' extension.
 *
 * @author	 <>
 * @package	TYPO3
 * @subpackage	tx_mtkatalogiadd
 */
class tx_mtkatalogiadd_pi2 extends tslib_pibase {
	var $prefixId      = 'tx_mtkatalogiadd_pi2';		// Same as class name
	var $scriptRelPath = 'pi2/class.tx_mtkatalogiadd_pi2.php';	// Path to this script relative to the extension dir.
	var $extKey        = 'mtkatalogi_add';	// The extension key.
	var $pi_checkCHash = true;
	
	/**
	 * The main method of the PlugIn
	 *
	 * @param	string		$content: The PlugIn content
	 * @param	array		$conf: The PlugIn configuration
	 * @return	The content that is displayed on the website
	 */
	function main($content, $conf) {
		$this->conf = $conf;
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();
		
	
		$content='
			<strong>This is a few paragraphs:</strong><br />
			<p>This is line 1</p>
			<p>This is line 2</p>
	
			<h3>This is a form:</h3>
			<form action="'.$this->pi_getPageLink($GLOBALS['TSFE']->id).'" method="POST">
				<input type="text" name="'.$this->prefixId.'[input_field]" value="'.htmlspecialchars($this->piVars['input_field']).'">
				<input type="submit" name="'.$this->prefixId.'[submit_button]" value="'.htmlspecialchars($this->pi_getLL('submit_button_label')).'">
			</form>
			<br />
			<p>You can click here to '.$this->pi_linkToPage('get to this page again',$GLOBALS['TSFE']->id).'</p>
		';
		$content='';
		

		$this->insert_project();
		//$this->parse_project();
		
		return $this->pi_wrapInBaseClass($content);
	}
	function insert_project()
	{
		$where = 'deleted=0 AND hidden=0 AND parse=1 AND pid='.$this->conf['project_pid'];
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,article,wwwcategory','tx_mtkatalogiadd_project',$where,'','',1);	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{
			//print_r($row);
			$this->add_newsto($row);
		}
	}
	function add_newsto($all)
	{
		$article=$all['article'];
		$uid=$all['uid'];
		$all_article=$this->get_all_article($article);
		
		$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['catlink_pid'].' AND project='.$uid;
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,link','tx_mtkatalogiadd_proincat',$where,'','RAND()',1);	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{
			//print_r($row);
			$art=$all_article[rand(0,count($all_article)-1)];
			$this->inset_to_seocat($art,$row);
		}
	}
	function inset_to_seocat($art,$row)
	{
		$link=$row['link'];
		$get=$this->get($link);
		//preg_match_all('#<td bgcolor=[^>]*>(.*)</td>#isU',$get,$return,PREG_SET_ORDER);
		#<input type="hidden"\s+name="sub[id]" value="(\S*)"#Usi
		preg_match_all('#<input type=\"hidden\" name=\"sub\[id\]\" value=\"(.*)\" \/>#isU',$get,$sub,PREG_SET_ORDER);
		$sub=$sub[0][1];
		preg_match_all('#<input type=\"hidden\" name=\"sub\[id_cat\]\" value=\"(.*)\" \/>#isU',$get,$cat,PREG_SET_ORDER);
		$cat=$cat[0][1];
		preg_match_all('#<input type=\"hidden\" name=\"sub\[title\]\" value=\"(.*)\" \/>#isU',$get,$title,PREG_SET_ORDER);
		$title=$title[0][1];

		list($www)=explode('/',str_replace('http://','',$link));
		//print_r($);
		$www='http://'.str_replace('//','',$www.'/?action=add');
		
		$post=array(
			'sub[id]'		=>	$sub,
			'sub[id_cat]'	=>	$cat,
			'sub[title]'	=>	$title,
			'new_site'		=>	'Wyślij',
			'site'			=>	$art['links']
		);
		
		$get=$this->getPage($www,$link,$post);
		preg_match_all('#src=\"http:\/\/api.recaptcha.net/(.*)\"#isU',$get,$recache,PREG_SET_ORDER);
		$recache='http://api.recaptcha.net/'.$recache[0][1];
		$code=$this->get($recache);

		if(stristr($code,'challenge'))
		{

		//	preg_match_all('#challenge : \'(.*)\',"#isU',$code,$getcode,PREG_SET_ORDER);
			list(,$code)=explode("challenge : '",$code);
			list($code)=explode("',",$code);
			if($code!='')
			{
				$post=array(
					'title'			=>	$this->mtgen_text_synonim(array($art['title'])),
					'description'	=>	$this->mtgen_text_synonim(array($art['bodytext'])),
					'keywords'		=>	$art['keywords'],
					//'site'			=>	$art['links'],
					'recaptcha_challenge_field'	=>	$code,
					'recaptcha_response_field'	=>	'test'
					
				);
				$getvalid=$this->getPage($www,'',$post);
				print_r($getvalid); exit;
			}
		}//else $this->insert_project();
		print_r($get);

	}
	function mtgen_text_synonim($str,$opt=0)
	{
		
		for($i=0; $i<count($str); $i++)
		{
			$text[$i]=generuj($str[$i]);
		}
		//if($opt==1) print_r($text);
		return $text;
	}
	function getPage ($url, $ref='', $post='')
	{
		//print_r($url);
		$ch = curl_init();
	
		if( !empty($post) )
		{
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		}
		else
		{
				curl_setopt($ch, CURLOPT_POST, 0);
		}
	
		if( empty($ref) or $ref == '' ) $ref = $url;
	
		curl_setopt($ch, CURLOPT_REFERER, $ref);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
		curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookiefile');
		curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookiefile');
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)");
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL, $url);
	
		$r = curl_exec($ch);
	
		return $r;
	}
	function get_all_article($article)
	{
		if(stristr($article,',')) $article=explode(',',$article);
		else $article=array($article);
		$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['article_pid'];
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('title,bodytext,links,keywords','tt_news',$where,'');	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{
			$add[]=$row;
		}
		return $add;
	}
	//
	function parse_project()
	{
		$where = 'deleted=0 AND hidden=0 AND parse=0 AND pid='.$this->conf['project_pid'];
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,article,wwwcategory','tx_mtkatalogiadd_project',$where,'');	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{
			$this->get_www_from_category($row['wwwcategory'],$row['uid']);
			$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_mtkatalogiadd_project', 'uid='.$row['uid'],array('parse'=>1));		
			$setres = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
		}

	}
	function get_www_from_category($cat,$project)
	{		
		$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['catlink_pid'].' AND category IN('.$cat.')';
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,link','tx_mtkatalogiadd_catlink',$where);	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{
			$add[]=$this->insert_wwwforproject($row['uid'],$project,$row['link']);
		}	
		return $add;
	}
	function insert_wwwforproject($catlink,$project,$link)
	{
		$uid=0;
		$where = 'pid='.$this->conf['catlink_pid'].' AND project='.$project.' AND link="'.mysql_real_escape_string($link).'"';
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tx_mtkatalogiadd_proincat',$where,'');	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{
			$uid=$row['uid'];
		}
		if($uid==0)
		{
			$add=array(
				'pid'		=>	$this->conf['catlink_pid'],
				'tstamp'	=>	time(),
				'crdate'	=>	time(),
				'project'	=>	$project,
				'category'	=>	$catlink,
				'link'		=>	$link
			);
	
			$GLOBALS['TYPO3_DB']->exec_INSERTquery(
				'tx_mtkatalogiadd_proincat',
				$add   			
			);
		
		return $GLOBALS['TYPO3_DB']->sql_insert_id();
		}
	}
	
	function get($url) 
	{
		$process = curl_init($url);
		curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
		curl_setopt($process, CURLOPT_HEADER, 0);
		curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
		if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
		if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
		curl_setopt($process,CURLOPT_ENCODING , $this->compression);
		curl_setopt($process, CURLOPT_TIMEOUT, 30000);
		if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
		curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
		$return = curl_exec($process);
		curl_close($process);
		return $return; 
	} 
	
}



if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mtkatalogi_add/pi2/class.tx_mtkatalogiadd_pi2.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mtkatalogi_add/pi2/class.tx_mtkatalogiadd_pi2.php']);
}

?>